#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#  Copyright (c) Huoty - All rights reserved
#
#      Author: Huoty <sudohuoty@gmail.com>
#  CreateTime: 2016-09-30 13:49:47
# *************************************************************

"""命令行版客户端"""

import os
import sys
import json
import time
import requests
from ..utils import md5, AESCipher


class KibotClient(object):
    def __init__(self, user, apikey, secret):
        self.user = "test" if "TEST" in os.environ else user
        self.apikey = os.environ["KIBOT_TEST_KEY"] if "TEST" in os.environ else apikey
        self.secret = os.environ["KIBOT_TEST_SEC"] if "TEST" in os.environ else secret

        if "TEST" in os.environ:
            self.url = "http://localhost:8002/api"
        else:
            self.url = "http://kibot.konghy.cn/api"

    def request_answer(self, question):
        timestamp = str(int(time.time()))
        aes_key = md5(self.secret + timestamp + self.apikey)
        param = {"info": question, "user": self.user}

        aes = AESCipher(aes_key)
        data = aes.encrypt(json.dumps(param))

        payload = {
            "key": self.apikey,
            "timestamp": timestamp,
            "data": data,
        }

        try:
            r = requests.post(self.url, json=payload, timeout=6)
            r.raise_for_status()
        except requests.exceptions.Timeout:
            answer = "Connection timeout!"
        except requests.exceptions.ConnectionError:
            answer = "Connection error!"
        except requests.exceptions.HTTPError:
            answer = "Invalid HTTP response!"
        except Exception as e:
            answer = e

        res = r.json()
        if res["code"] != 12000:
            return res["msg"]
        return res["data"]

    def ask(self, msg):
        answer = self.request_answer(msg)
        if isinstance(answer, dict):
            return answer["text"].strip()
        else:
            return answer.strip()


def main():
    from argparse import ArgumentParser
    from ..utils import Colorizing
    parser = ArgumentParser(description="The command line version of the kibot client")
    parser.add_argument("-u", "--user", required=True, help="user name")
    parser.add_argument("-k", "--apikey", help="allocated kibot api key")
    parser.add_argument("-s", "--secret", help="allocated secret")

    options = parser.parse_args()

    kibot_cli = KibotClient(**vars(options))
    _c = Colorizing()

    import readline  # 增强控制台模式，使能够搜索历史查询记录
    while True:
        try:
            if sys.version_info[0] < 3:
                text = raw_input(_c('%s> ' % options.user, "green"))
            else:
                text = input(_c('%s> ' % options.user, "green"))
            print(_c("kibot:", "yellow"), _c(kibot_cli.ask(text), "magenta"))
        except KeyboardInterrupt:  # Ctrl + C
            print()
            continue
        except EOFError:  # Ctrl + D
            break

    print("\nBye")


# Script starts from here

if __name__ == "__main__":
    main()
